package www.sofn.com.member;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import www.sofn.com.accounts.domain.vo.WeChatUserInfoVO;
import www.sofn.com.member.domain.po.MemberPO;

import java.io.Serializable;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;

@Service
public class MemberService {

    @Resource
    private MemberMapper memberMapper;
    public Boolean exitOpenid(Serializable openid) {
        return memberMapper.exitOpenid(openid);
    }
    @Transactional
    public void registerMember(WeChatUserInfoVO weChatUserInfoVO) {
        MemberPO memberPO = BeanUtil.toBean(weChatUserInfoVO, MemberPO.class);
        memberPO.setIntegral(BigDecimal.ZERO.setScale(2));
        memberPO.setIsMember(0).setRegisterDate(LocalDateTime.now()).setHeadImgUrl(weChatUserInfoVO.getHeadimgurl());
        memberMapper.insert(memberPO);
    }

    public MemberPO getMemberByOpenid(Serializable openid) {
     return  memberMapper.selectOne(new LambdaQueryWrapper<MemberPO>().eq(MemberPO::getOpenid,openid));
    }

    @Transactional
    public void  updateMemberIntegral(BigDecimal integral,String memberId){
        memberMapper.updateMemberIntegral(integral,memberId);
    }

    @Transactional
    public void  addMemberIntegral(BigDecimal integral,Serializable memberId){
        final MemberPO memberPO = getMemberByOpenid(memberId);
        if(ObjectUtil.isNull(memberPO)) return ;
        memberPO.setIntegral(memberPO.getIntegral().setScale(2, RoundingMode.FLOOR).add(integral));
        memberMapper.updateMemberIntegral(integral,memberId);
    }

    @Transactional
    public void  makeMember(String memberId){ //成为会员
        memberMapper.updateMemberStatus(memberId);
    }


}
